<?php

class PathTool
{
	static function getName($path)
	{		
		$pos = strrpos($path,"\\");
		if($pos == false) $pos = strrpos($path,"/");
		if($pos == false) return $path;
		
		return substr($path,$pos+1);
	}
	
	static function getExtention($path)
	{		
		$parts = pathinfo( $path);
		$ext = $parts["extension"];//ext,jpg,gif,exe
		//$ext = strtolower($ext);
		return $ext;
	}
	
	static function urlencode_safe($txt)
	{
		$txt = str_replace("\\", "/", $txt);//urlencode会将\\解析成\ 
		$txt = urlencode($txt);
		return str_replace("+","%20",$txt);
	}
	
	static function urlencode_path($txt)
	{
		$txt = str_replace("\\", "/", $txt);//urlencode会将\\解析成\
		$txt = str_replace("/", "\\\\", $txt); 
		$txt = urlencode($txt);
		$txt = str_replace("+","%20",$txt);
		return $txt;		
	}
	
	static function urldecode_path($txt)
	{
		$txt = str_replace("+","%20",$txt);
		$txt = urldecode($txt);
		return $txt;
	}
	
	static function combin($p1,$p2)
	{
		$str_len = strlen($p1);//总长度
		//以/结尾
		if($str_len-1 == strrpos($p1, "/") )
		{
			return $p1 . $p2;			
		}
		return $p1 . "/" . $p2;
	}
	
	static function to_utf8($str)
	{
		$encode = mb_detect_encoding($str, array('CP936','ASCII','GB2312','GBK','BIG5','UTF-8'));
		if($encode == "UTF-8" ) return $str;
		
		return iconv($encode, 'UTF-8', $str);
	}
	
	static function to_gbk($str)
	{
		$encode = mb_detect_encoding($str, array('CP936','ASCII','GB2312','GBK','BIG5','UTF-8'));
		if( $encode == "GBK" ) return $str;
		if( $encode == "CP936" ) return $str;

		return mb_convert_encoding($str, "GBK", $encode);
		//return iconv($encode, 'GBK', $str);
	}
	
	//将多字节转换为utf8
	static function unicode_decode($str)
	{
		return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
				create_function(
						'$matches',
						'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
				),
				$str);
	}
	
	static function BytesToString($byteCount)
	{
	    $suf = array( "B", "KB", "MB", "GB", "TB", "PB", "EB" );
	    if ($byteCount == 0)
	        return "0" + $suf[0];
        $bytes = abs($byteCount);
        $place = (int)(floor(log($bytes, 1024)));
        $num = round($bytes / pow(1024, $place), 1);
        return $num. $suf[$place];
	}

	public static function mkdir($dir)
	{
		//在windows平台需要转换成多字节编码
		if(StringTool::iequals(PHP_OS,"WINNT"))
			$dir = iconv('UTF-8', 'GBK', $dir);

	    if(is_dir($dir) && file_exists($dir)) return true;
		if(!mkdir($dir,0777,true))
		{
			return false;
		}

		return true;
	}
	

	public static function mkdirsFromFile(/*string*/$f)
	{
		$dir = dirname($f);
		PathTool::mkdir($dir);
	}
}
?>
